package com.kaluli.project.controller;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kaluli.project.domain.entity.KllProductVo;
import com.kaluli.project.service.KllMainOrderService;
import com.kaluli.project.service.KllProductService;
import com.kaluli.project.service.KllZZOpService;
import com.kaluli.project.utils.MD5Utils;
import com.kaluli.project.utils.RegexUtil;
import com.kaluli.project.utils.nanshaxml.XmlFanli;

/**
 * 
 * 超级返接口
 * 
 * @author niwei
 * 
 */
@Controller
@PropertySource({ "classpath:config.properties" })
public class FanliController {

	private static Logger log = Logger.getLogger(FanliController.class);

	@Autowired
	private Environment env;

	@Autowired
	private KllProductService kllProductService;
	
	@Autowired
	private KllMainOrderService kllMainOrderService;
	
	@Autowired
	private KllZZOpService kllZZOpService;

	@RequestMapping(value = "/fanliApi")
	@ResponseBody
	public String fanliApi(@RequestParam(value = "id", required = true) String id, @RequestParam(value = "timestamp", required = false) String timestamp, @RequestParam(value = "sign", required = false) String sign) throws NoSuchAlgorithmException {
		String result = "";

		if (id == null) {
			result = "{'status':'error','message':'商品为空!'}";
			return result;
		}
		// timestamp 校验
		/*
		 * if(!StringUtils.isBlank(timestamp)){ if(!RegexUtil.isDate(timestamp,
		 * "yyyy-mm-dd HH:mm:ss")){
		 * result="{'status':'error','message':'timestamp格式不正确!'}"; return
		 * result; } }
		 */

		// sign校验
		if (sign != null && !"".equals(sign)) {
			// 校验sign是不是大写
			if (!RegexUtil.isCapital(sign)) {
				result = "{'status':'error','message':'sign不是大写!'}";
				return result;
			}
			String key = "XXX";
			String signkey = id + timestamp + key;
			String singture = MD5Utils.MD5_32bit(signkey);
			if (!singture.equals(sign)) {
				result = "{'status':'error','message':'标签不正确!'}";
				return result;
			}
		}

		KllProductVo product = kllProductService.findById(id);
		if (product != null) {

			// 拼接 xml格式串
			String root = XmlFanli.ROOT;
			XmlFanli xml = XmlFanli.getInstance();
			xml.addBody("id", product.getId(), true, root);
			xml.addBody("title", "<![CDATA[" + product.getTitle() + "]]>", true, root);
			xml.addBody("category", "", true, root);
			xml.addBody("url", env.getProperty("pc.product.url") + id + ".html", true, root);
			xml.addBody("url_wap", env.getProperty("m.product.url") + id + ".html", true, root);
			xml.addBody("price", product.getPrice(), true, root);
			xml.addBody("promotion_price", product.getDiscountPrice(), true, root);
			xml.addBody("wap_price", "", true, root);
			xml.addBody("detail", "<![CDATA[" + product.getContent() + "]]>", true, root);
			xml.addBody("status", product.getStatus(), true, root);
			xml.addBody("pic_main", "", false, root);
			xml.addBody("img", "", false, root + "/pic_main");
			xml.addBody("url", "<![CDATA[" + product.getPic() + "]]>", true, root + "/pic_main/img");
			xml.addBody("size", "400*400", true, root + "/pic_main/img");
			xml.addBody("pic_extra", "", false, root);
			String picDetail = product.getPicDetail();
			if (picDetail != null && !"".equals(picDetail)) {
				String json = picDetail.substring(4);
				String arr[] = json.split(";");
				for (int i = 0; i < arr.length; i++) {
					if (arr[i].startsWith("s:101")) {
						System.out.println();
						xml.addBody("img", "", false, root + "/pic_extra");
						xml.addBody("url", "<![CDATA[" + arr[i].substring(6) + "]]>", true, root + "/pic_extra/img");
						xml.addBody("size", "400*400", true, root + "/pic_extra/img");
					}
				}
			}
			result = xml.toString();
			result = result.replace("&lt;", "<");
			result = result.replace("&gt;", ">");
			System.out.println(result);
		} else {
			result = "{'status':'error','message':'获取商品信息失败!'}";
		}

		log.info(result);

		return result;

	}

	@RequestMapping(value = "/orders")
	@ResponseBody
	public String geiOrders(@RequestParam(required = false) String channel_id, @RequestParam(required = false) Date begin_date, @RequestParam(required = false) Date end_date, @RequestParam(required = false) String order_id, @RequestParam(required = false) int status, @RequestParam(required = false) String code) {
		String result = "";
		result = kllMainOrderService.findKllMainOrderByChannel(channel_id,begin_date,end_date,order_id,code);
		return result;
	}
	
	@RequestMapping(value = "/getnum")
	@ResponseBody
	public String getNum(@RequestParam(required = true) String nums) {
		String result = "";
		result = kllZZOpService.getNums(nums);
		return result;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    dateFormat.setLenient(false);
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:允许输入空值，false:不能为空值
	}
}
